package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class TaskServiceImpl implements TaskService {
    @Autowired
    private TaskinfoMapper taskinfoMapper;
    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;
    @Autowired
    private CacheService cacheService;


    /**
     * 添加任务
     *
     * @param task 任务对象
     * @return 任务id
     */
    @Override
    public long addTask(Task task) {

        //1.添加数据带数据库中
        Boolean success = saveTaskToDb(task);

        if (success){
            //1.添加任务到redis中
            saveTaskToCache(task);
        }

        return task.getTaskId();
    }

    /**
     * 取消任务
     *
     * @param taskId
     */
    @Override
    public boolean cancelTask(long taskId) {
        if (taskId != 0){
            throw new RuntimeException("参数错误");
        }

        //删除任务表数据,并更新日志表中的状态
        Task task = updateDb(taskId,ScheduleConstants.EXECUTED);

        if (task != null){
            //删除redis中的任务
            removeTaskFromCache(task);
        }

        return false;
    }

    /**
     * 拉取任务
     *
     * @param type
     * @param priority
     */
    @Override
    public Task poll(int type, int priority) {

        Task task = null;

        try {
            String key = type + "_" + priority;
            String task_json = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
            if (StringUtils.isNotBlank(task_json)){
                task = JSON.parseObject(task_json, Task.class);
                task.setTaskType(ScheduleConstants.EXECUTED);
                //修改日志库中的状态
                updateDb(task.getTaskId(),ScheduleConstants.EXECUTED);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("拉取任务有误");
        }

        return task;
    }

    /**
     * 删除redis中的任务
     * @param task
     */
    private void removeTaskFromCache(Task task) {
        //以任务类型与优先级拼接为key
        String key = task.getTaskType() + "_" + task.getPriority();

        if (task.getExecuteTime() <= System.currentTimeMillis()){
            cacheService.lRemove(ScheduleConstants.TOPIC+key,0,JSON.toJSONString(task));
        }else{
            cacheService.zRemove(ScheduleConstants.FUTURE+key,JSON.toJSONString(task));
        }


    }

    private Task updateDb(long taskId,int start) {
        Task task = null;
        try {
            //通过taskId删除任务表中的数据
            taskinfoMapper.deleteById(taskId);

            //通过taskId修改日志表中的状态
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(start);
            taskinfoLogsMapper.updateById(taskinfoLogs);

            //创建task对象
            task = new Task();
            BeanUtils.copyProperties(taskinfoLogs,task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        } catch (Exception e) {
            log.error("task cancel exception taskid={}",taskId);
        }
        return task;
    }

    /**
     * 添加数据到redis中
     * @param task
     */
    private void saveTaskToCache(Task task) {
        //以任务类型与优先级拼接为key
        String key = task.getTaskType() + "_" + task.getPriority();

        //获取五分钟以后的时间
        //获取创建时间的一个对象
        Calendar calendar = Calendar.getInstance();
        //添加时间(单位为分钟),获取五分钟后的时间
        calendar.add(Calendar.MINUTE,5);
        long timeInMillis = calendar.getTimeInMillis();

        //如果执行时间小于当前时间,加入list中
        if (task.getExecuteTime() <= System.currentTimeMillis()){
            cacheService.lLeftPush(ScheduleConstants.TOPIC+key, JSON.toJSONString(task));
            //如果执行时间大于大于当前时间,并且小于预设时间(5分钟后)
        }else if (task.getExecuteTime() > System.currentTimeMillis() && task.getExecuteTime() <= timeInMillis){
            cacheService.zAdd(ScheduleConstants.FUTURE+key,JSON.toJSONString(task),task.getExecuteTime());
        }

    }

    /**
     * 添加数据到数据库
     * @param task
     * @return
     */
    private Boolean saveTaskToDb(Task task) {
        boolean flag = false;

        try {
            //添加任务到任务库
            //创建taskinfo对象
            Taskinfo taskinfo = new Taskinfo();
            //属性拷贝
            BeanUtils.copyProperties(task,taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            //修改数据库
            taskinfoMapper.insert(taskinfo);

            //设置taskID
            task.setTaskId(taskinfo.getTaskId());

            //添加数据到日志库
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            //属性拷贝
            BeanUtils.copyProperties(taskinfo,taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(taskinfoLogs);

            flag = true;
        } catch (BeansException e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 未来数据定时刷新
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh() {

        String token = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);
        if (StringUtils.isNotBlank(token)) {
            log.info("执行了未来数据定时刷新");

            //获取未来数据中的所有key
            Set<String> futurekeys = cacheService.scan(ScheduleConstants.FUTURE + "*");

            for (String futurekey : futurekeys) {

                String topic_key = ScheduleConstants.TOPIC + "_" + futurekey.split(ScheduleConstants.FUTURE)[0];
                //获取改组key下的需要消费的任务,通过分数判断(分数通过时间设置)
                Set<String> set = cacheService.zRangeByScore(futurekey, 0, System.currentTimeMillis());
                if (!set.isEmpty()) {
                    //把需要消费的数据加入list队列中
                    cacheService.refreshWithPipeline(futurekey, topic_key, set);
                }
            }
            log.info("未来数据想list中同步成功");
        }
    }

    /**
     * 数据库定时同步任务
     */
    //五分钟调用一次
    @Scheduled(cron = "0 */5 * * * ?")
    //开机自启
    @PostConstruct
    public void reloadData(){
        clearCache();
        //获得五分钟后的时间
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MINUTE,5);

        //查找小于未来五分钟的数据
        List<Taskinfo> taskinfos = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().lt(Taskinfo::getExecuteTime, instance.getTime()));
        if (taskinfos!=null&&taskinfos.size()>0){
            for (Taskinfo taskinfo : taskinfos) {
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo,task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                //调用添加任务中的方法,将数据添加到redis中
                saveTaskToCache(task);
            }
        }
    }

    //清空redis中的所有任务
    private void clearCache() {
        cacheService.delete(ScheduleConstants.TOPIC+"*");
        cacheService.delete(ScheduleConstants.FUTURE+"*");
    }
}
